package xyz.ablue.wscaller.data;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
import org.mapdb.Serializer;

import java.io.File;
import java.util.NavigableSet;

/**
 * <p>
 * MapDB
 * </p>
 *
 * @author: kancy
 * @date: 2019/10/26 18:55
 **/
public class MapDB {
    private static DB db;
    private static HTreeMap<String, String> configCacheMap;
    private static NavigableSet<String> wsdlSets;
    static {
        initdb();
        configCacheMap = db.hashMap("configCacheMap",Serializer.STRING, Serializer.STRING);
        wsdlSets = db.treeSet(Constrants.WSDL_SETS, Serializer.STRING);

        initConfigMap();
    }

    private static void initdb() {
        File file = null;
        try {
            file = new File(String.format("%s/%s",System.getProperty("user.home") , "mapdb2_webservice_ui.db")
                    .replaceAll("\\+","/"));
            db = DBMaker.fileDB(file)
                    .fileMmapEnableIfSupported()
                    .fileMmapCleanerHackEnable()
                    .fileMmapPreclearDisable()
                    .make();
            addAutoCloseShutdownHook();
            System.out.println(String.format("数据文件成功加载：%s", file.getAbsolutePath()));
        } catch (Exception e) {
            System.out.println(String.format("正在自动修复这个问题：", e.getMessage()));
            file.delete();
            initdb();
        }
    }

    private static void initConfigMap() {
        try {
            configCacheMap.putIfAbsent(Constrants.WS_AUTH_REH_LABEL, Constrants.WS_AUTH_REH_DEF_VALUE);
            configCacheMap.putIfAbsent(Constrants.WS_AUTH_USER_LABEL, Constrants.WS_AUTH_USER_LABEL_DEF_VALUE);
            configCacheMap.putIfAbsent(Constrants.WS_AUTH_PASSWD_LABEL, Constrants.WS_AUTH_PASSWD_LABEL_DEF_VALUE);
            configCacheMap.putIfAbsent(Constrants.WS_AUTH_USER, Constrants.WS_AUTH_USER_DEF_VALUE);
            configCacheMap.putIfAbsent(Constrants.WS_AUTH_PASSWD, Constrants.WS_AUTH_PASSWD_DEF_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void addAutoCloseShutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                getDb().commit();
                getDb().close();
                System.out.println("db commit and close success ！");
            }
        });
    }

    public static DB getDb() {
        return db;
    }

    public static HTreeMap<String,String> getConfigMap(){
        return configCacheMap;
    }

    public static NavigableSet<String> getWsdlSets() {
        return wsdlSets;
    }
}
